package com.zwg.git_customview.viewpager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.zwg.git_customview.R

/**
 * viewpager的基本使用
 */
class ViewPagerActivity : ComponentActivity() {

    var mViewPager: ViewPager? = null

    var mData: MutableList<Int>? = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
    }

    private fun initData() {
        mData?.add(R.mipmap.nba1)
        mData?.add(R.mipmap.nba2)
        mData?.add(R.mipmap.nba3)
        mViewPager?.adapter?.notifyDataSetChanged()
        //设置起始位置
        mViewPager?.setCurrentItem(Int.MAX_VALUE / 2)
    }

    private fun initView() {
        mViewPager = findViewById(R.id.view_pager)
        mViewPager?.adapter = mData?.let { MyPagerAdapter(it) }
    }

    class MyPagerAdapter(var mData: MutableList<Int>) : PagerAdapter() {
        override fun getCount(): Int {
//            return mData.size ?: 0
            //无线轮播
            return Int.MAX_VALUE
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {

            return view === `object`
        }

        /**
         * 初始化
         */
        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            //无限轮播
            var realPositon = position % mData.size
            //1%3 = 1
            //2%3 = 2
            //3%3 = 0
            var view = LayoutInflater.from(container.context)
                .inflate(R.layout.item_pager, container, false)
            var iv = view.findViewById<ImageView>(R.id.cover)
            iv.setImageResource(mData.get(realPositon))
            //已经有老爸了
            //java.lang.IllegalStateException: The specified child already has a parent.
            // You must call removeView() on the child's parent first.
            if (iv.parent is ViewGroup) {
                (iv.parent as ViewGroup)
                    .removeView(iv)
            }
            container.addView(iv)
            return iv
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

    }

}
